import ButtonManager from './ButtonManager.js';

const ComplianceAppealTakeDown = {
  buttonId: 'appealTakeDown',
  defaultText: '9. 违规申诉商品下架',

  init() {
    document.getElementById(this.buttonId).addEventListener('click', this.handleClick.bind(this));
  },

  async handleClick() {
    ButtonManager.updateButtonState(this.buttonId, '9. 违规申诉商品下架处理中...', true);
    ButtonManager.disableAllButtons(this.buttonId);

    try {
      // 获取所有必要参数
      const { antiContent, mallId, appealdata } = await new Promise(resolve => {
        chrome.storage.local.get(['antiContent', 'mallId', 'appealdata'], resolve);
      });

      if (!antiContent || !mallId) throw new Error('缺少鉴权参数');
      if (!appealdata?.length) throw new Error('请先获取申诉数据');

      const [tab] = await chrome.tabs.query({ active: true, currentWindow: true });

      const results = await chrome.scripting.executeScript({
        target: { tabId: tab.id },
        func: executeTakeDown,
        args: [mallId, antiContent, appealdata]
      });

      if (results?.[0]?.result) {
        const { success, failed } = results[0].result;
        alert(`下架完成！成功:${success}条，失败:${failed}条,确认阅读反馈记录`);
      }
      console.log('反馈记录读')
      const readFeeds = await chrome.scripting.executeScript({
        target: { tabId: tab.id },
        func: readFeed,
        args: [mallId, antiContent],
      });
      if (readFeeds?.[0]?.result) {
        const { success } = readFeeds[0].result;
        alert(`反馈记录读取完成${success}条`)
      }

    } catch (error) {
      console.error("下架失败:", error);
      alert(error.message);
    } finally {
      console.log(123456)
      ButtonManager.resetButtonState(this.buttonId, this.defaultText);
      ButtonManager.enableAllButtons();
    }
  }
};

// 执行下架逻辑
function executeTakeDown(j_mallid, j_anti_content, j_spuArr) {
  return new Promise(resolve => {
    let j_arrindexs = 0;
    let j_success = 0; 
    let j_failed = 0;
    let j_errorSkcs = [];
    let j_time = Math.floor(Math.random() * 2)*100 + 500

    let j_date = new Date();
    let j_year = j_date.getFullYear().toString();
    let j_month = (j_date.getMonth() + 1).toString();
    let j_day = j_date.getDate().toString();
     
    // 对月份和日期进行补零
    j_month = j_month.length === 1 ? '0' + j_month : j_month;
    day = j_day.length === 1 ? '0' + j_day : j_day;

    let j_dateTime = j_year + j_month + j_day;

    let j_downNum = 0 // 计算下架条数
    let j_downMaxNum = 10 // 最大限制下架条数
    console.log('j_spuArr',j_spuArr)
    function j_list() {
      if (j_arrindexs >= j_spuArr.length || j_downNum > j_downNum) {
        return resolve({ success: j_success, failed: j_failed, errors: j_errorSkcs });
      }
      console.log('j_arrindexs', j_arrindexs)
      setTimeout(function(){
        j_pageQuery(j_spuArr[j_arrindexs]);
      },j_time)
    }

    // 通过spu查询全部商品的skc
    function j_pageQuery(arr) {
      if (!arr?.length) {
        j_arrindexs++;
        setTimeout(function(){
          j_list();
        },j_time)
        
        return;
      }

      fetch("https://seller.kuajingmaihuo.com/bg-visage-mms/product/skc/pageQuery", {
        method: 'POST',
        headers: {
          'anti-content': j_anti_content,
          'mallid': j_mallid,
          'content-type': 'application/json'
        },
        body: JSON.stringify({
          page: 1,
          pageSize: 100,
          productIds: arr
        })

        
      })
      .then(res => res.json())
      .then(data => {
        if (data.success) {
          // 全部的skcid
          const allSkcIds = data.result.pageItems.map(item => item.productSkcId.toString());
          console.log(j_arrindexs,'全部商品的skc', allSkcIds)
          setTimeout(function(){
            j_pageQuery2(arr,allSkcIds)
          },j_time)
          
        } else {
          console.error('查询失败:', data.errorMsg);
          j_arrindexs++;
          setTimeout(function(){
            j_list();
          },j_time)
          
        }
      })
      .catch(error => {
        console.error('查询异常:', error);
        j_arrindexs++;
        setTimeout(function(){
          j_list();
        },j_time)
      });
    }

    // 通过spu查询已下架商品的skc
    function j_pageQuery2(arr,allSkcIds){
      fetch("https://seller.kuajingmaihuo.com/bg-visage-mms/product/skc/pageQuery", {
        method: 'POST',
        headers: {
          'anti-content': j_anti_content,
          'mallid': j_mallid,
          'content-type': 'application/json'
        },
        body: JSON.stringify({
          page: 1,
          pageSize: 100,
          skcSecondaryStatus: 1,
          skcTopStatus: 200,
          productIds: arr
        })
        
      })
      .then(res => res.json())
      .then(data => {
        if (data.success) {

          const isDownSkcIds = data.result.pageItems.map(item => item.productSkcId.toString()); // 已下架的skcid

          const isDownSet = new Set(isDownSkcIds); // 预先创建 Set
          const notDownSkcIds = allSkcIds.filter(id => !isDownSet.has(id)); // 未下架的商品skcid
          console.log(j_arrindexs,'未下架商品的skc', notDownSkcIds)
          // 执行下架方法
          setTimeout(function(){
            j_submitFeedback(notDownSkcIds, 0);
          },j_time)
          
          
        } else {
          console.error('查询失败:', data.errorMsg);
          j_arrindexs++;
          setTimeout(function(){
            j_list();
          },j_time)
          
        }
      })
      .catch(error => {
        console.error('查询异常:', error);
        j_arrindexs++;
        setTimeout(function(){
          j_list();
        },j_time)
      });
    }


    // 执行下架操作
    function j_submitFeedback(arr, index) {
      if (index >= arr.length) {
        j_arrindexs++;
        setTimeout(function(){
          j_list();
        },j_time)
        return;
      }

      fetch("https://seller.kuajingmaihuo.com/marvel-mms/cn/api/kiana/ultraman/FeedbackMmsExecuteRpcService/submitFeedback", {
        method: 'POST',
        headers: {
          'anti-content': j_anti_content,
          'mallid': j_mallid,
          'content-type': 'application/json'
        },
        body: JSON.stringify({
          feedbackType: 1,
          productSkcId: arr[index],
          feedbackProblemType: 27,
          remark: "图片上传错误，申请下架"+ j_dateTime,
          feedbackDimension: 2
        })
      })
      .then(res => res.json())
      .then(data => {
        if (data.success) {
          j_success++;
          j_downNum++
        } else {
          j_failed++;
          j_errorSkcs.push(arr[index]);
        }
        setTimeout(function(){
          j_submitFeedback(arr, index + 1);
        },j_time)
        
      })
      .catch(error => {
        j_failed++;
        j_errorSkcs.push(arr[index]);
        setTimeout(function(){
          j_submitFeedback(arr, index + 1);
        },j_time)
        
      });
    }
    setTimeout(function(){
      j_list();
    },j_time)
    
  });
}

// 将反馈处理成已读
function readFeed(j_mallid, j_anti_content){
  return new Promise(resolve => {
    let j_pageNum = 1
    let j_pageSize = 40
    let j_body = {"feedbackStatus":1,"pageNo":j_pageNum,"pageSize":j_pageSize,"haveRead":0}
    let j_feedbackIdList = []
    let j_time = Math.floor(Math.random() * 2)*100 + 500
    // 获取未读反馈列表
    function j_queryFeedbackList(){
      j_body.pageNo = j_pageNum
      fetch("https://seller.kuajingmaihuo.com/marvel-mms/cn/api/kiana/ultraman/FeedbackMmsQueryRpcService/queryFeedbackList", {
        "headers": {
          "accept": "*/*",
          "accept-language": "zh-CN,zh;q=0.9",
          "anti-content": j_anti_content,
          "cache-control": "max-age=0",
          "content-type": "application/json",
          "mallid": j_mallid,
          "priority": "u=1, i",
          "sec-ch-ua": "\"Chromium\";v=\"134\", \"Not:A-Brand\";v=\"24\", \"Google Chrome\";v=\"134\"",
          "sec-ch-ua-mobile": "?0",
          "sec-ch-ua-platform": "\"macOS\"",
          "sec-fetch-dest": "empty",
          "sec-fetch-mode": "cors",
          "sec-fetch-site": "same-origin"
        },
        "referrer": "https://seller.kuajingmaihuo.com/",
        "referrerPolicy": "strict-origin-when-cross-origin",
        "body": JSON.stringify(j_body),
        "method": "POST",
        "mode": "cors",
        "credentials": "include"
      }).then(res => res.json())
      .then(data => {
        if (data.success) {
          
          let { mallFeedbackInfoVOList,total } = data.result
          if(mallFeedbackInfoVOList.length>0){
            mallFeedbackInfoVOList.forEach((item,index)=>{
              j_feedbackIdList.push(item.feedbackId)
            })
            console.log('feedbackIdList',j_feedbackIdList)
            if(j_pageNum < Math.ceil(total/j_pageSize)){
              j_pageNum++;
              setTimeout(function(){
                j_queryFeedbackList();
              },j_time)
              
            } else{
              // 分块处理结果
              const chunkedArr = [];
              for (let i = 0; i < j_feedbackIdList.length; i += 100) {
                chunkedArr.push(j_feedbackIdList.slice(i, i + 100));
              }
              setTimeout(function(){
                j_queryFeedbackReply(chunkedArr,0)
              },j_time)
              
            }
          } else{
            console.log('没有未读反馈记录')
            location.reload();
          }
        } else {
          console.error('查询失败:', data.errorMsg);
          j_pageNum++;
          setTimeout(function(){
            j_queryFeedbackList();
          },j_time)
          
        }
      })
      .catch(error => {
        console.error('查询异常:', error);
        j_pageNum++;
        setTimeout(function(){
          j_queryFeedbackList();
        },j_time)
        
      });
    }

    // 
    function j_queryFeedbackReply(arr, i){
      let index = i
      if(index >= arr.length){
        console.log('未读反馈记录已全部阅读')
        alert('未读反馈记录已全部阅读')
        location.reload();
        return
      }
      
      fetch("https://seller.kuajingmaihuo.com/marvel-mms/cn/api/kiana/ultraman/FeedbackMmsExecuteRpcService/readFeedbackReply", {
        "headers": {
          "accept": "*/*",
          "accept-language": "zh-CN,zh;q=0.9",
          "anti-content": j_anti_content,
          "cache-control": "max-age=0",
          "content-type": "application/json",
          "mallid": j_mallid,
          "priority": "u=1, i",
          "sec-ch-ua": "\"Chromium\";v=\"134\", \"Not:A-Brand\";v=\"24\", \"Google Chrome\";v=\"134\"",
          "sec-ch-ua-mobile": "?0",
          "sec-ch-ua-platform": "\"macOS\"",
          "sec-fetch-dest": "empty",
          "sec-fetch-mode": "cors",
          "sec-fetch-site": "same-origin"
        },
        "referrer": "https://seller.kuajingmaihuo.com/",
        "referrerPolicy": "strict-origin-when-cross-origin",
        "body": JSON.stringify({"feedbackIdList": arr[index]}),
        "method": "POST",
        "mode": "cors",
        "credentials": "include"
      })
      .then(res => res.json())
      .then(data => {
        if (data.success) {
          if(index < arr.length){
            index++
            setTimeout(function(){
              j_queryFeedbackReply(arr,index)
            },j_time)
            
          } else{
            return resolve({ success: j_feedbackIdList.length });
          }
          
        } else {
          console.error('查询失败:', data.errorMsg);
        }
      })
      .catch(error => {
        console.error('查询异常:', error);
      })
    }
    setTimeout(function(){
      j_queryFeedbackList()
    },j_time)
  })
}

export default ComplianceAppealTakeDown;